﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SmartCard.Framework.CardFeatures;
using SmartCard.Framework;
using System.Windows;

namespace SmartCardClient.ViewModels.Features
{
	internal class RawApduViewModel : FeatureViewModel
	{
		private RawCommandFeature _feature;

		public RawApduViewModel(RawCommandFeature feature)
			: base("Raw Commands")
		{
			if (feature == null)
			{ throw new ArgumentNullException("feature"); }

			_feature = feature;
			SendCommand = new RelayCommand<object>((x) => OnSendCommand());
		}

		#region properties

		/// <summary>
		/// Get the instruction class
		/// </summary>
		public byte InstructionClass
		{ get; set; }

		/// <summary>
		/// Get the instruction code
		/// </summary>
		public byte InstructionCode
		{ get; set; }

		/// <summary>
		/// Get param 1
		/// </summary>
		public byte Param1
		{ get; set; }

		/// <summary>
		/// Get Param 2
		/// </summary>
		public byte Param2
		{ get; set; }

		/// <summary>
		/// Command data, with a max length up to 65,535
		/// bytes of data
		/// </summary>
		public string CommandData
		{ get; set; }

		/// <summary>
		/// Max response length with a max value of
		/// 65,535
		/// </summary>
		public ushort MaxResponseLength
		{ get; set; }

		#endregion

		#region commands

		public RelayCommand<object> SendCommand
		{ get; set; }

		#endregion

		private void OnSendCommand()
		{
			try
			{
				var bytes = ConvertHextStringToBytes(CommandData);

				var apdu = new ApduCommand(InstructionClass, InstructionCode,
					Param1, Param2, bytes, MaxResponseLength);

				var response = _feature.ExecuteRaw(apdu);

				StringBuilder sb = new StringBuilder();
				sb.AppendFormat("SW1={0}{1}", response.Sw1, Environment.NewLine);
				sb.AppendFormat("SW1={0}{1}", response.Sw2, Environment.NewLine);
				sb.AppendFormat("RESPONSE={0}{1}", response.Data, Environment.NewLine);
				MessageBox.Show(sb.ToString());
			}
			catch (SmartCardException ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private byte[] ConvertHextStringToBytes(string hexString)
		{
			var arrayLength = hexString.Length / 2;
			byte[] bytes = new byte[arrayLength];

			for (int i = 0; i < arrayLength; ++i)
			{
				bytes[i] = Convert.ToByte(
					hexString.Substring((i*2), 2), 16);
			}
			return bytes;
		}
	}
}
